package wang.snalc.jpanewdemon.specification_new;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@SuppressWarnings({"UnusedReturnValue"})
public class SpecificationBuilder<T> {


    public Specification<T> build(SearchCriteria searchCriteria) {
        if (searchCriteria != null) {
            if (searchCriteria.getSearchCriteriaSet() == null) {
                return buildOne(searchCriteria);
            } else {

                return buildMany(searchCriteria);
            }
        } else {
            return null;
        }
    }

    Specification<T> buildOne(SearchCriteria searchCriteria) {
        return new CommonSpecification<>(searchCriteria);
    }

    Specification<T> buildMany(SearchCriteria searchCriteria) {
        Specification<T> result = null;
        List<Specification> specificationList = new ArrayList<>();
        for (SearchCriteria criteria : searchCriteria.getSearchCriteriaSet()) {

            Specification<T> specification;
            if (criteria.getSearchCriteriaSet() != null) {
                specification = buildMany(criteria);
            } else {
                specification = buildOne(criteria);
            }
            if (result == null) {
                if (!searchCriteria.getIsOr()) {
                    specificationList.add(specification);
                } else {
                    result = Specification.where(specification);
                }
            } else {
                if (searchCriteria.getIsOr()) {
                    result = Specification.where(result).or(specification);
                } else {
                    specificationList.add(specification);
                }
            }

        }
        if (specificationList.size() > 0) {
            Specification<T> specification = new CommonSpecification<>(searchCriteria);
            if (result == null) {
                result = Specification.where(specification);
            } else {
                result = Specification.where(result).and(specification);
            }
        }
        return result;
    }

}
